#!/bin/sh

. "$TEST_SHELL_PATH/abstract-dbops"

RUN_SCRIPT_PATH="$PROJECT_PATH/src/main/resources/templates/run-major-version-upgrade.sh"
SET_RESULT_SCRIPT_PATH=""
OP_NAME=majorVersionUpgrade
NORMALIZED_OP_NAME='major version upgrade'
KEBAB_OP_NAME='major-version-upgrade'
PATRONI_CONTAINER_NAME=patroni
MAJOR_VERSION_UPGRADE_CONTAINER_NAME=major-version-upgrade
POSTGRES_VERSION_KEY=stackgres.io/postgresql-version
SOURCE_VERSION=11.8
TARGET_VERSION=12.6
TARGET_EXTENSIONS=[]
TARGET_POSTGRES_CONFIG=postgresconf-12
DATA_CHECKSUM=true
PG_UPGRADE_PATH="/var/lib/postgresql/upgrade"
PG_RELOCATED_BASE_PATH="/var/lib/postgresql/relocated"
PG_EXTENSIONS_BASE_PATH="/var/lib/postgresql/extensions"

shell_unit_test_skip() {
  if [ -z "$IMAGE_NAME" ] && echo "$IMAGE_NAME" | grep "patroni"
  then
    return 0;
  else
    return 1;
  fi
}

shell_unit_test_dbops_major_version_upgrade_setup() {
  (
  echo "pod/test-0"
  echo "pod/test-1"
  ) > "$TEST_TARGET_PATH/cluster_pods"
  echo false > "$TEST_TARGET_PATH/pod_0_restarted"
  echo false > "$TEST_TARGET_PATH/pod_1_restarted"
  echo "pod/test-0" > "$TEST_TARGET_PATH/primary_pod"
}

shell_unit_test_dbops_major_version_upgrade() {
  shell_unit_test_dbops_major_version_upgrade_setup
  shell_unit_test_dbops
}

mock kubectl kubectl_mock

kubectl_mock() {
  mokked
  case "$*" in
    ("get $CLUSTER_CRD_NAME.$CRD_GROUP "*" --template="'
  LOCK_POD='*'
  LOCK_TIMEOUT='*'
  RESOURCE_VERSION={{ .metadata.resourceVersion }}
  ')
    echo '
      LOCK_POD=test
      LOCK_TIMEOUT='"$(( $(date +%s) + 1 ))"'
      RESOURCE_VERSION=test
      '
    ;;
    ("annotate $CLUSTER_CRD_NAME "*)
    ;;
    ("get $CLUSTER_CRD_NAME.$CRD_GROUP -n $CLUSTER_NAMESPACE $CLUSTER_NAME --template={{ if .status.dbOps }}{{ if .status.dbOps.$OP_NAME }}true{{ end }}{{ end }}")
    ;;
    ("get $CLUSTER_CRD_NAME.$CRD_GROUP -n $CLUSTER_NAMESPACE $CLUSTER_NAME --template={{ .status.postgresVersion }}")
    printf '%s' "$SOURCE_VERSION"
    ;;
    ("get $CLUSTER_CRD_NAME.$CRD_GROUP -n $CLUSTER_NAMESPACE $CLUSTER_NAME --template={{ .spec.configurations.sgPostgresConfig }}")
    printf %s "postgresconf"
    ;;
    ("get $CLUSTER_CRD_NAME.$CRD_GROUP -n $CLUSTER_NAMESPACE $CLUSTER_NAME --template={{ if .status }}{{ if .status.backupPaths }}{{ index .status.backupPaths 0 }}{{ end }}{{ end }}")
    printf %s "sgbackup.stackgres.io/$CLUSTER_NAMESPACE/$CLUSTER_NAME/${SOURCE_VERSION%.*}"
    ;;
    ("get $CLUSTER_CRD_NAME.$CRD_GROUP -n $CLUSTER_NAMESPACE $CLUSTER_NAME --template={{ .spec.replication.mode }}")
    printf %s async
    ;;
    ("get $CLUSTER_CRD_NAME.$CRD_GROUP -n $CLUSTER_NAMESPACE $CLUSTER_NAME -o json")
      echo '{
              "apiVersion": "stackgres.io/v1",
              "kind": "SGCluster",
              "metadata": {
                  "name": "'"$CLUSTER_NAME"'",
                  "namespace": "'"$CLUSTER_NAMESPACE"'"
              },
              "spec": {
                  "instances": 2,
                  "postgres": {
                    "version": "11.8"
                  },
                  "sgInstanceProfile": "size-s"
              },
              "status": {
                "postgresVersion": "11.8",
                "dbOps": {
                  "majorVersionUpgrade": {
                    "check": false,
                    "clone": false,
                    "dataChecksum": '"$DATA_CHECKSUM"',
                    "encoding": "UTF8",
                    "initialInstances": [
                        "'"$CLUSTER_NAME-0"'",
                        "'"$CLUSTER_NAME-1"'"
                    ],
                    "link": false,
                    "locale": "C.UTF-8",
                    "primaryInstance": "'"$CLUSTER_NAME-0"'",
                    "sourcePostgresVersion": "11.8",
                    "targetPostgresVersion": "12.6"
                  }
                }
              }
            }'
    ;;
    ("patch --dry-run $CLUSTER_CRD_NAME.$CRD_GROUP -n $CLUSTER_NAMESPACE $CLUSTER_NAME --type merge -p "*)
    ;;
    ("replace --raw /apis/$CRD_GROUP/v1/namespaces/$CLUSTER_NAMESPACE/$CLUSTER_CRD_NAME/$CLUSTER_NAME -f"*)
    ;;
    ("get $DBOPS_CRD_NAME -n $CLUSTER_NAMESPACE $DBOPS_NAME --template={{ if .status }}true{{ else }}false{{ end }}")
    printf '%s' false
    ;;
    ("get $DBOPS_CRD_NAME -n $CLUSTER_NAMESPACE $DBOPS_NAME --template={{ if .status.$OP_NAME }}replace{{ else }}add{{ end }}")
    printf '%s' add
    ;;
    ("get $DBOPS_CRD_NAME -n $CLUSTER_NAMESPACE $DBOPS_NAME -o json")
      echo '{
        "apiVersion": "stackgres.io/v1",
        "kind": "SGDbOps",
        "metadata": {
          "name": "'"$DBOPS_NAME"'",
          "namespace": "'"$CLUSTER_NAMESPACE"'",
          "resourceVersion": "1",
          "uid": "172381f8-3f37-46c9-9a29-8284a73d1e5e"
        },
        "spec": {
          "sgCluster": "'"$CLUSTER_NAME"'",
          "op": "majorVersionUpgrade"
        }
      }'
    ;;
    ("create --raw /api/v1/namespaces/$CLUSTER_NAMESPACE/events -f"*)
    ;;
    ("get pods -n $CLUSTER_NAMESPACE -l $CLUSTER_POD_LABELS -o name")
    cat "$TEST_TARGET_PATH/cluster_pods"
    ;;
    ("get pods -n $CLUSTER_NAMESPACE -l $CLUSTER_PRIMARY_POD_LABELS -o name")
    cat "$TEST_TARGET_PATH/primary_pod"
    ;;
    ("get pod -n $CLUSTER_NAMESPACE test-0 -o name")
    echo "pod/test-0"
    ;;
    ("get pod -n $CLUSTER_NAMESPACE test-1 -o name")
    echo "pod/test-1"
    ;;
    ("get pod -n $CLUSTER_NAMESPACE test-0 --template={{ .metadata.annotations.status }}")
    echo '"pending_restart":false'
    ;;
    ("get pod -n $CLUSTER_NAMESPACE test-1 --template={{ .metadata.annotations.status }}")
    echo '"pending_restart":false'
    ;;
    ("get pod -n $CLUSTER_NAMESPACE test-0 --template={{ index .metadata.labels \"controller-revision-hash\" }}")
    if [ "$(cat "$TEST_TARGET_PATH/pod_0_restarted")" = "true" ]
    then
      echo hash-1
    else
      echo hash-0
    fi
    ;;
    ("get pod -n $CLUSTER_NAMESPACE test-1 --template={{ index .metadata.labels \"controller-revision-hash\" }}")
    if [ "$(cat "$TEST_TARGET_PATH/pod_1_restarted")" = "true" ]
    then
      echo hash-1
    else
      echo hash-0
    fi
    ;;
    ("get sts -n $CLUSTER_NAMESPACE $CLUSTER_NAME --template={{ .status.updateRevision }}")
    echo "hash-1"
    ;;
    ("get sts -n $CLUSTER_NAMESPACE $CLUSTER_NAME -o json")
    echo '{
      "spec": {
        "template": {
          "metadata": {
            "annotations": {
              "stackgres.io/postgresql-version": "12.6"
            }
          },
          "spec": {
            "initContainers": [{
              "name": "major-version-upgrade"
            }]
          }
        }
      }
    }'
    ;;
    ("patch $CLUSTER_CRD_NAME.$CRD_GROUP -n $CLUSTER_NAMESPACE $CLUSTER_NAME --type=json -p "*"{\"op\":\"replace\",\"path\":\"/spec/instances\",\"value\":1}"*)
    (
    cat "$TEST_TARGET_PATH/primary_pod"
    ) > "$TEST_TARGET_PATH/cluster_pods"
    ;;
    ("patch $CLUSTER_CRD_NAME.$CRD_GROUP -n $CLUSTER_NAMESPACE $CLUSTER_NAME --type=json -p "*"{\"op\":\"replace\",\"path\":\"/spec/instances\",\"value\":2}"*)
    (
    echo "pod/test-0"
    echo "pod/test-1"
    ) > "$TEST_TARGET_PATH/cluster_pods"
    ;;
    ("patch $DBOPS_CRD_NAME -n $CLUSTER_NAMESPACE $DBOPS_NAME "*)
    ;;
    ("wait pod -n $CLUSTER_NAMESPACE test-"*" --for condition=Ready --timeout 0")
    ;;
    ("delete pod -n $CLUSTER_NAMESPACE test-0")
    echo true > "$TEST_TARGET_PATH/pod_0_restarted"
    ;;
    ("delete pod -n $CLUSTER_NAMESPACE test-1")
    echo true > "$TEST_TARGET_PATH/pod_1_restarted"
    ;;
    ("exec -n $CLUSTER_NAMESPACE $CLUSTER_NAME-"*" -c $PATRONI_CONTAINER_NAME -- psql -q -t -A -c SELECT setting FROM pg_settings WHERE name = 'lc_collate' UNION ALL SELECT datcollate FROM pg_database WHERE datname = 'template1' LIMIT 1")
    echo 'en_US.UTF-8'
    ;;
    ("exec -n $CLUSTER_NAMESPACE $CLUSTER_NAME-"*" -c $PATRONI_CONTAINER_NAME -- psql -q -t -A -c SHOW server_encoding")
    echo 'UTF8'
    ;;
    ("exec -n $CLUSTER_NAMESPACE $CLUSTER_NAME-"*" -c $PATRONI_CONTAINER_NAME -- psql -q -t -A -c SELECT CASE WHEN current_setting('data_checksums')"*)
    echo '"true"'
    ;;
    ("exec -n $CLUSTER_NAMESPACE $CLUSTER_NAME-"*" -c $PATRONI_CONTAINER_NAME -- sh -c rm -rf \"$PG_UPGRADE_PATH/$SOURCE_VERSION/data\""*)
    ;;
    ("exec -n $CLUSTER_NAMESPACE $CLUSTER_NAME-"*" -c $PATRONI_CONTAINER_NAME -- psql -q -t -A -c CHECKPOINT -c CHECKPOINT")
    echo 'en_US.UTF-8'
    ;;
    *)
    not_mokked
    ;;
  esac
}
